package dpImage
{
    import flash.display.BitmapData;
    import flash.events.Event;
    import flash.net.URLRequest;
    
    import mx.controls.Alert;
    import mx.controls.Image;
    import mx.events.FlexEvent;

    public class DpImage extends Image
    {
        private static const MAX_DIMENSION:uint = 2880;
//        private static const MAX_HEIGHT:uint = 2880;     
        private var _url:String;        
        private var _bitmapData:BitmapData;   
        private var _width:Number;
        private var _height:Number;
        
        public function DpImage(url:String)
        {
            _url = url;
            this.addEventListener(Event.INIT, eInit);
            this.addEventListener(Event.COMPLETE, eComplete);
            this.addEventListener(FlexEvent.CREATION_COMPLETE, eComplete);
            super();
            this.source = _url;
        }

        private function eInit(e:Event):void {        
            this.loaderInfo.addEventListener(Event.COMPLETE, eLoadComplete);
            var req:URLRequest = new URLRequest(_url);
            this.load(req);    
        }
        public function eComplete(e:FlexEvent):void {
            this.loaderInfo.addEventListener(Event.COMPLETE, eLoadComplete);
            var req:URLRequest = new URLRequest(_url);
            this.load(req);    
        }

        private function eLoadComplete(e:Event):void {
            _width = e.target.width;
            _height = e.target.height;
        }        
        
//        public function get ThumbBitmapData():BitmapData {
//            if(this.content) {
//            var bmd:BitmapData = new BitmapData(180, 250);
//            bmd.draw(this.content);
//            return bmd;
//            }
//            else
//                return null;
//        }
//        public function get ThumbBitmap():Bitmap {
//            if(! content) {
//                return null;
//            }
//            var bmd:BitmapData = new BitmapData(180, 240);
//            bmd.draw(this);
//            return new Bitmap(bmd);
//        }
        
        public function get DpBitmapData():BitmapData {
            if(_bitmapData) {
                return _bitmapData;
            }
            if(! this.loaderInfo) {
                Alert.show("Wants bitmap with no loaderInfo: " + this._url);
                return null;
            }
            var w:Number = width;
            var h:Number = height;
            var imax:Number = Math.max(width, height);
            if(imax < MAX_DIMENSION) {
                w *= (imax / MAX_DIMENSION) ;
                h *= (imax / MAX_DIMENSION) ;
            }
            _bitmapData = new BitmapData(w, h);
            _bitmapData.draw(this);
            return _bitmapData;
        }
    }
}